package com.gack.helper.common.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.gack.business.vo.UpdateModel;

import net.sf.json.JSONObject;
import sun.misc.BASE64Encoder;

public class JPushRestAPI {
	private static final Logger log = LoggerFactory.getLogger(JPushRestAPI.class);
    private String masterSecret = "62237ea0baf9db54d1be0b99";
    private String appKey = "dde685abb543dcc27de8f744";
    private String pushUrl = "https://api.jpush.cn/v3/push";    
    private boolean apns_production = true;    
    private int time_to_live = 86400;
    
    public void setApns_production(boolean apns_production) {
    	this.apns_production = apns_production;
    }
    public boolean getApns_production() {
    	return this.apns_production;
    }
	
    public JSONObject SendPush(String alert,String mesType, Object content,String sound, Object audience) {
    	JSONObject jsonObject = jsonDataStr(alert, mesType, content, sound, audience, apns_production, time_to_live);
    	String resultData = push(this.pushUrl, this.appKey, this.masterSecret, jsonObject.toString());
    	JSONObject result = JSONObject.fromObject(resultData);
    	 if(result.containsKey("error")){
    		 if(audience instanceof String){
    			 log.info("针对全部设备平台的信息推送失败！");
    			 JSONObject error = JSONObject.fromObject(result.get("error"));
    			 log.info("错误信息为：" + error.get("message").toString());
    		 }
    		 if(audience instanceof JSONObject){
    			 JSONObject jAudience = (JSONObject)audience;
    			 log.info("针对别名为" + jAudience.getJSONArray("alias") + "的信息推送失败！");
    			 JSONObject error = JSONObject.fromObject(result.get("error"));
    			 log.info("错误信息为：" + error.get("message").toString());
    		 }
         }
    	 System.out.println("------推送了一条alert为"+alert+"mesType"+mesType+"content"+content+"sound"+sound+"时间"+new Date());
    	return result;
    }
	
	 /** 
　　　　* BASE64加密工具
　　　　*/
     @SuppressWarnings("restriction")
	public  String encryptBASE64(String str) {
         byte[] key = str.getBytes();
       BASE64Encoder base64Encoder = new BASE64Encoder();
       String base64_auth_string = base64Encoder.encodeBuffer(key);
         return base64_auth_string;
     }
     
     /**
      * 发送Post请求（json格式）
      * @param reqURL
      * @param data
      * @param encodeCharset
      * @param authorization
      * @return result
      */
     @SuppressWarnings({ "resource" })
     public  String sendPostRequest(String reqURL, String data, String encodeCharset,String authorization){
         HttpPost httpPost = new HttpPost(reqURL);
         HttpClient client = new DefaultHttpClient();
         HttpResponse response = null;
         String result = "";
         try {
              StringEntity entity = new StringEntity(data, encodeCharset);
              entity.setContentType("application/json");
              httpPost.setEntity(entity);
              httpPost.setHeader("Authorization",authorization.trim());
              response = client.execute(httpPost);
              result = EntityUtils.toString(response.getEntity(), encodeCharset);
         } catch (Exception e) {
             log.error("请求通信[" + reqURL + "]时偶遇异常,堆栈轨迹如下", e);  
         }finally{
             client.getConnectionManager().shutdown();
         }
         return result;
     }
    
     
     public  JSONObject androidData(String alert,String key, Object value) {
    	 JSONObject android = new JSONObject();//android通知内容
         android.put("alert", alert);
         android.put("builder_id", 1);
         JSONObject android_extras = new JSONObject();//android额外参数
         android_extras.put("content", value);
         android_extras.put("mesType", key);
         android.put("extras", android_extras);
         return android;
     }
     
     public  JSONObject iosData(String alert,String key, Object value, String sound) {
    	 JSONObject ios = new JSONObject();//ios通知内容
         ios.put("alert", alert);
         ios.put("sound", sound);
         if (sound != null && sound.equals("")) {
        	 ios.put("badge", "");
         } else {
        	 ios.put("badge", "+1");
         }
         
         JSONObject ios_extras = new JSONObject();//ios额外参数
         ios_extras.put("content", value);
     	ios_extras.put("mesType", key);
         ios.put("extras", ios_extras);
         return ios;
     }
     
     public  JSONObject jsonDataByOneAlias(String alias) {
    	 JSONObject audience = new JSONObject();//推送目标
         JSONArray alias1 = new JSONArray();
         alias1.add(alias);
         audience.put("alias", alias1);
    	 return audience;
     }
     
     public  JSONObject jsonDataByManyAlias(List<String> alias) {
    	 JSONObject audience = new JSONObject();//推送目标
         JSONArray alias1 = new JSONArray();
         alias1.addAll(alias);
         audience.put("alias", alias1);
    	 return audience;
     }
     
     public  JSONObject jsonDataStr(String alert, String key, Object value, String sound, Object audience, boolean apns_production,int time_to_live) {
    	 JSONObject json = new JSONObject();
    	 JSONArray platform = new JSONArray();//平台
         platform.add("android");
         platform.add("ios");
         JSONObject notification = new JSONObject();//通知内容
         notification.put("android", androidData(alert, key, value));
         notification.put("ios", iosData(alert, key, value, sound));
         JSONObject options = new JSONObject();//设置参数
         options.put("time_to_live", Integer.valueOf(time_to_live));
         options.put("apns_production", apns_production);
       
         json.put("platform", platform);
         json.put("audience", audience);
         json.put("notification", notification);
         json.put("options", options);
         
         return json;
     }
     
     
     /**
      * 推送方法-调用极光API
      * @param reqUrl
      * @param alias
      * @param alert
      * @return result
      */
     public  String push(String reqUrl, String appKey, String masterSecret, String data){
         String base64_auth_string = encryptBASE64(appKey + ":" + masterSecret);
         String authorization = "Basic " + base64_auth_string;
         return sendPostRequest(reqUrl,data,"UTF-8",authorization);
     }
     
     public static void main(String[] args) {
    	 ArrayList<String> list = new ArrayList<>();
    	 list.add("17601010656");
    	 list.add("18843013258");
    	 list.add("15136492717");
    	 list.add("13260150995");
    	 JPushRestAPI jPushRestAPI = new JPushRestAPI();
    	 System.out.println(jPushRestAPI.jsonDataByManyAlias(list));
//    	 jPushRestAPI.SendPush("推送", "", "", "Default", jPushRestAPI.jsonDataByManyAlias(list));
    	 jPushRestAPI.setApns_production(false);
    	 UpdateModel model  = new UpdateModel();
    	 model.setConferenceCode("4234fdf");
    	 jPushRestAPI.SendPush("测试一下啊", "12", null, "Default", jPushRestAPI.jsonDataByOneAlias("13718911088"));
    	 
		
		
	}

}
